package com.hyzh.latte.sand;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author songkui
 * @since 2024/4/22 18:03
 */
public class SandSessionManager {
    //key sessionId
    private final ConcurrentHashMap<String, SandClient> sessionMap = new ConcurrentHashMap<>();
    //key userId
    private final ConcurrentHashMap<String, SandClient> pcMap = new ConcurrentHashMap<>();
    //key userId
    private final ConcurrentHashMap<String, Set<SandClient>> mtListMap = new ConcurrentHashMap<>();

    private SandSessionManager(){}

    private static final class ManagerHolder {
        static final SandSessionManager manager = new SandSessionManager();
    }
    public static SandSessionManager getInstance(){
        return SandSessionManager.ManagerHolder.manager;
    }

    public void putPcMap(SandClient client){
        pcMap.put(client.getUserId(), client);
        sessionMap.put(client.getSessionId(), client);
    }

    public void putMt(SandClient client){
        Set<SandClient> list = mtListMap.computeIfAbsent(client.getUserId(), k -> new HashSet<>());
        list.add(client);
        sessionMap.put(client.getSessionId(), client);
    }

    public SandClient getSandClient(String sessionId){
        return sessionMap.get(sessionId);
    }

    public Set<SandClient> getMtList(String userId){
        return mtListMap.get(userId);
    }

    public SandClient getPcClient(String userId){
        return pcMap.get(userId);
    }

    public void removeBySessionId(String SessionId){
        SandClient client = sessionMap.get(SessionId);
        if (null == client){
            return;
        }

        if (SandClientTypeEnum.MT.equals(client.getTypeEnum())){
            Optional.ofNullable(mtListMap.get(client.getUserId())).ifPresent(c -> c.remove(client));
        }else {
            pcMap.remove(client.getUserId());
        }
    }


}
